package com.tarry.shop.goods.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarry.shop.common.ResultEntity;
import com.tarry.shop.goods.entity.Goods;
import com.tarry.shop.goods.service.IGoodsService;
import com.tarry.shop.validation.Add;
import com.tarry.shop.validation.Query;
import com.tarry.shop.validation.Update;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TARRY
 * @since 2021-11-27
 */
@RestController
@RequestMapping("/goods")
@Api("商品信息")
@Validated
public class GoodsController {
    @Autowired
    IGoodsService goodsService;

    @GetMapping("/queryList")
    @ApiOperation(value = "分页查询信息")
    public ResultEntity<IPage<Goods>> pageList(Page<Goods> page,
                                               @Validated(value = Query.class) Goods goods){
        OrderItem id = OrderItem.asc("id");
        page.setOrders(Arrays.asList(id));
        IPage<Goods> goodsPage = goodsService.page(page,goods);
        return ResultEntity.success(goodsPage);
    }

    @GetMapping("/getGoodsById")
    @ApiOperation(value = "根据商品ID查询商品信息")
    public ResultEntity<Goods> getUserById(@ApiParam(required = true,value = "商品Id")
                                               @NotNull(message = "ID不能为空")
                                               Integer goodsId){
        Goods goods = goodsService.getById(goodsId);
        return ResultEntity.success(goods);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加商品")
    public ResultEntity<Goods> addUser(@Validated(value = Add.class) Goods goods){
        goodsService.save(goods);
        return ResultEntity.success(goods);
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新商品信息")
    public ResultEntity<Goods> updateUser(@Validated(value = Update.class) Goods goods){
        goodsService.updateById(goods);
        return ResultEntity.success(goods);
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "删除商品")
    public ResultEntity<Boolean> delete(@ApiParam(required = true,value = "商品Id")
                                            @NotNull(message = "ID不能为空") Integer goodsId){
        return ResultEntity.success(goodsService.removeById(goodsId));
    }


}
